<?php
/*
 * template name: payment
 */
//redirect to paypal
if(isset($_GET['i']) && $_GET['i']){
    $infoQuote = RequestAQoute::listRequestAqouteByIdRequestAquote($_GET['i']);
    $quantity = count(unserialize($infoQuote[0]->start_location));    
    
    if($infoQuote){
	Paypal::redirectPaypal($quantity, $infoQuote[0]->price, $infoQuote[0]->id_request_a_quote);
    }
}

//when paypal return data
if(isset($_GET['token']) && $_GET['token'] && isset($_GET['PayerID']) && $_GET['PayerID']){    
    $token = trim($_GET['token']);
    $payerId = trim($_GET['PayerID']);    
    $obPaypal = new Paypal();
    $obPaypal->set();    
    $obInvoice = new Invoice;
    //update model
    $infoInvoice = $obInvoice->getByToken($token);

    if (!$infoInvoice) {
	//error!!
	redirectTo404Page();
    }

    $result = $obPaypal->GetExpressCheckoutDetails($token);

    $result['PAYERID'] = $payerId;
    $result['TOKEN'] = $token;
    $result['ORDERTOTAL'] = $infoInvoice[0]->total_purchased;

    //Detect errors
    if (!$obPaypal->isCallSucceeded($result)) {
	if ($obPaypal->apiLive === true) {
	    //Live mode basic error message
	    $error = 'We were unable to process your request. Please try again later';
	} else {
	    //Sandbox output the actual error message to dive in.
	    $error = $result['L_LONGMESSAGE0'];
	}
	echo $error;
	exit();
    } else {
	$paymentResult = $obPaypal->DoExpressCheckoutPayment($result);

	//Detect errors
	if (!$obPaypal->isCallSucceeded($paymentResult)) {
	    if ($obPaypal->apiLive === true) {
		//Live mode basic error message
		$error = 'We were unable to process your request. Please try again later';
	    } else {
		//Sandbox output the actual error message to dive in.
		$error = $paymentResult['L_LONGMESSAGE0'];
	    }
	    echo $error;
	    exit();
	} else {

	    //payment was completed successfully
	    //update payment status
	    $aInvoice['payment_info'] = serialize($paymentResult); //get information about transaction	    
	    
	    $obInvoice->update($aInvoice, $token);
	    wp_redirect(get_permalink(107));
	    
	}
    }
}